package com.cml.client.common.config;


import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Configuration {
    private Logger logger = Logger.getLogger(Configuration.class);



    private static String RC_SERVER_ID = "rc.server.id";


    private String configFileName="rc-client.properties";

    private static String RC_SERVER_FOLLOWER_LIST = "rc.server.follower_list";

    private static String SERVICE_NAME = "service.name";

    private static String SERVICE_HEARTBEAT_INTERVAL_TIME="service.heartbeat.interval.time";



    private String nodeFollowerServerList;

    private String serviceName;

    private int serviceHeartbeatIntervalTime=3000;

    private Integer httpPort;

    private Configuration(){

    }

    public Integer getHttpPort() {
        if(httpPort == null){
            return 0;
        }
        return httpPort;
    }

    public void setHttpPort(Integer httpPort) {
        this.httpPort = httpPort;
    }

    public int getServiceHeartbeatIntervalTime() {
        return serviceHeartbeatIntervalTime;
    }

    public void setNodeFollowerServerList(String nodeFollowerServerList) {
        this.nodeFollowerServerList = nodeFollowerServerList;
    }

    public String getServiceName() {
        return serviceName;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }




    public void parse(String configFileName) throws IOException {
        if(StringUtils.isNotEmpty(configFileName)){
            this.configFileName = configFileName;
        }
        logger.info("当前使用配置文件为："+this.configFileName);
        InputStream fileInputStream =null;
        try {
            fileInputStream =  Configuration.class.getClassLoader().getResourceAsStream(this.configFileName);
            Properties properties = new Properties();
            properties.load(fileInputStream);
            this.nodeFollowerServerList= (String) properties.get(Configuration.RC_SERVER_FOLLOWER_LIST);
            logger.info("配置参数"+Configuration.RC_SERVER_FOLLOWER_LIST + ":"+nodeFollowerServerList);

            this.serviceName= (String) properties.get(Configuration.SERVICE_NAME);
            logger.info("配置参数"+Configuration.SERVICE_NAME + ":"+serviceName);

            this.serviceHeartbeatIntervalTime= Integer.decode((String) properties.get(Configuration.SERVICE_HEARTBEAT_INTERVAL_TIME));
            logger.info("配置参数"+Configuration.SERVICE_HEARTBEAT_INTERVAL_TIME + ":"+serviceHeartbeatIntervalTime);


            validateConfigArg(this.validateNodeServerList(),Configuration.RC_SERVER_FOLLOWER_LIST);

        } catch (IOException e) {
            throw new ConfigurationException(e.getMessage());
        } finally {
            if (fileInputStream != null){
                fileInputStream.close();;
            }
        }
    }

    private void validateConfigArg(boolean status,String arg){
        if(!status){
            logger.error(arg+"配置错误");
            throw new ConfigurationException(arg+"配置错误");
        }
    }

    private boolean validateNodeServerList(){
        boolean verifyStatus= false;
        List<Map> nodeFollowerServerListData = getNodeFollowerServerList();
        if(nodeFollowerServerListData.size() > 0){
            for(Map nodeFollowerServer : nodeFollowerServerListData){
                String regex="^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])"
                        +"(\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)){3}$";
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher((String) nodeFollowerServer.get("ip"));
                boolean isMatched = matcher.matches();
                if(isMatched){
                    try {
                        Integer.parseInt((String) nodeFollowerServer.get("port"));
                        verifyStatus=true;
                    } catch (NumberFormatException e) {
                        logger.error(e);
                    }
                }
            }
        }
        return verifyStatus;
    }

    public List getNodeFollowerServerList() {
        List<Map> nodeFollowerServerListData = new ArrayList<Map>();
        if(StringUtils.isNotEmpty(nodeFollowerServerList)) {

            String[] nodeServerListSplit = this.nodeFollowerServerList.split(",");
            for (int i = 0; i < nodeServerListSplit.length; i++) {
                String[] nodeServerSplit = nodeServerListSplit[i].split(":");
                Map nodeFollowerServerMap = new HashMap();
                nodeFollowerServerMap.put("ip", nodeServerSplit[0]);
                nodeFollowerServerMap.put("port", nodeServerSplit[1]);
                nodeFollowerServerListData.add(nodeFollowerServerMap);
            }
        }
        return nodeFollowerServerListData;
    }

    private static class Singleton{
        private static Configuration INSTANCE = new Configuration();
    }

    public static Configuration getInstance(){
        return Singleton.INSTANCE;
    }

}
